const router = require('koa-router')()

const {
    getList,
    addPhone,
    getPhone,
    editPhone,
    getPhoneItem
} = require('../controller/phones')
// const loginCheck = require('../middleware/loginCheck')

const { SuccessModel, ErrorModel } = require('../model/resModel')

router.prefix('/api/phones')

router.get('/list', async function (ctx, next) {
    console.log(ctx.state, 'sssssssssssss')
    let name = ctx.query.name || ''
    const remark = ctx.query.remark || ''
    const listData = await getList(name, ctx.state.user.id)
    console.log('数据', listData)
    ctx.body = new SuccessModel(listData)

})

router.post('/add', async function (ctx, next) {
    console.log(ctx.request)
    let name = ctx.request.body.name || ''
    let tel = ctx.request.body.tel || ''
    if (!name && !tel) {
        ctx.body = new ErrorModel('名字和号码不能和为空')
        return
    }
    let remark = ctx.request.body.remark || ''
    const phone = await getPhone(tel)
    if (phone.length) {
        ctx.body = new ErrorModel('已经存在此号码')
        return;
    }
    const listData = await addPhone(name, tel, remark)
    console.log(listData)
    ctx.body = new SuccessModel(listData)

})

router.post('/edit', async function (ctx, next) {
    console.log(ctx.request)
    let name = ctx.request.body.name || ''
    let tel = ctx.request.body.tel || ''
    let id = ctx.request.body.id || ''
    if (!name && !tel) {
        ctx.body = new ErrorModel('名字和号码不能和为空')
        return
    }
    let remark = ctx.request.body.remark || ''
    const phone = await getPhoneItem(id)
    if (!phone.length) {
        ctx.body = new ErrorModel('暂无可修改的数据')
        return;
    }
    const listData = await editPhone(id, name, tel, remark)
    console.log(listData)
    ctx.body = new SuccessModel(listData)

})

module.exports = router